import javax.crypto.Cipher;
import java.io.*;
import java.net.*;
import java.security.Key;

public class Client {
    public static void main(String args[]) {
        System.out.println("客户端启动...");
        //while (true) {
        Socket mysocket;
        DataInputStream in = null;
        DataOutputStream out = null;
        try {
            mysocket = new Socket("192.168.56.1", 2019);
            in = new DataInputStream(mysocket.getInputStream());
            out = new DataOutputStream(mysocket.getOutputStream());
            System.out.println("请输入:");
            String str = new BufferedReader(new InputStreamReader(System.in)).readLine();

            MyBC turner = new MyBC(str);
            String infix;
            infix=turner.doTrans();
            StringBuilder newInfix = new StringBuilder(infix.replace(" ",""));
            for (int i = 1; i < infix.length()+(i+1)/2 ; i=i+2) {
                newInfix.insert(i," ");
            }

            String str1=newInfix.toString();//DES加密
            String a=null;
            FileInputStream f=new FileInputStream("key1.dat");
            ObjectInputStream b=new ObjectInputStream(f);
            Key k=(Key)b.readObject( );
            Cipher cp=Cipher.getInstance("DESede");
            cp.init(Cipher.ENCRYPT_MODE, k);
            byte ptext[]=str1.getBytes("UTF8");
            byte ctext[]=cp.doFinal(ptext);
            for(int i=0;i<ctext.length;i++){
                a+=String.valueOf(ctext[i]);
            }
            FileOutputStream f2=new FileOutputStream("SEnc.dat");
            f2.write(ctext);

            out.writeUTF(a);//调用toString()方法,返回newInflx的String值，以便调用writeUTF方法
            String s = in.readUTF();   //in读取信息，堵塞状态
            System.out.println("客户收到服务器的回答:" + s);
            Thread.sleep(500);//在500毫秒数让当前正在执行的线程休眠
        } catch (Exception e) {
            System.out.println("服务器已断开" + e);
        }
        //}
    }
}
